<?php
class FileUtils {

	private $directories;

	private $classes;

	function loadDirectories($directory) {
		global $directories;
			
		if( $directories == null ) $directories = array();
			
		if( is_dir( $directory ) ) {
			Logger::debug($this, "Adicionando o diretorio <b>$directory</b> a lista de processamento");
			$directories[] = $directory;
			$dirs = scandir($directory);

			foreach ( $dirs as $dir ) {
				$dir = $directory . "/" . $dir;
				if( is_dir($dir) && substr($dir, strlen($dir)- 1) != "." && substr($dir, strlen($dir)- 2) != ".." ) {
					loadDirectories($dir);
				}
			}
		}
	}

	function loadClasses() {
		global $directories, $classes, $root;
			
		foreach( $directories as $directory ) {
			Logger::debug($this, "Processando o diretorio <b>$directory</b>");

			$files = scandir($directory);
			foreach( $files as $file ) {
				$file = $directory . "/" . $file;
				Logger::debug($this, "Arquivo encontrado: '$file'");
				$extension = substr($file, strlen($file)-4, strlen($file));
					
				if( is_file($file) && $extension == ".php" ) { // verifica se e arquivo e se e php
					$include_file = str_replace($root . "/", "", $file);
					Logger::debug($this, "dicionando a classe $include_file ao classpath");
					$classes[] = $file;
				}
			}
		}
	}

	public static function createFile($path, $name, $content) {
		$filename = "$path/$name";
			
		$handle = fopen($filename, "w");
		fwrite($handle, $content);
		fclose($handle);
	}

	public static function createDirectory($path) {
		if( !file_exists($path) && !mkdir($path) ) {
			die('Failed to create folder ' . $path);
		}
	}

	public static function readFile($sFilename/*, $sCharset = 'UTF-8'*/) {
		if (floatval(phpversion()) >= 4.3) {
			$sData = file_get_contents($sFilename);
		} else {
			if (!file_exists($sFilename)) return -3;

			$rHandle = fopen($sFilename, 'r');
			if (!$rHandle) return -2;

			$sData = '';
			while(!feof($rHandle))
			$sData .= fread($rHandle, filesize($sFilename));

			fclose($rHandle);
		}

		/*if ($sEncoding = mb_detect_encoding($sData, 'auto', true) != $sCharset)
		 $sData = mb_convert_encoding($sData, $sCharset, $sEncoding);
		 */
		return $sData;
	}

	public static function loadFileInArray($path) {
		$handle = @fopen($path, "r");
		$lines = array();
			
		if ($handle) {
			while (!feof($handle)) {
				$lines[] = fgets($handle, 4096);
			}

			fclose($handle);
		}
		return $lines;
	}

	public static function loadPropertyInArray($path) {
		$arr = self::loadFileInArray($path);
		$text = array();
		for( $i = 0 ; $i < sizeof($arr); $i++ ) {
			$linha = $arr[$i];
			$key = trim(substr($linha, 0, strpos($linha, "=")));
			$value = trim(substr($linha, strpos($linha, "=") + 1, strlen($linha)));
			$text[$key] = ltrim($value);
		}
		return $text;
	}

	public static function listFiles($path) {
		$files = scandir($path);
		sort($files);
		return $files;
	}

	public static function includeFile($file) {
		ini_set("track_errors", 1);
		$php_errormsg = '';
		$result = @include($file);
		if ($php_errormsg != '') {
			$location = Messages::getConfig("appconfig.generic.error.page");
			Logger::debug("FileUtils.php", "Problem including " . $file);
			Logger::debug("FileUtils.php","Direcionando a request para a pagina $location");
			header("Location: " . $location);
			Scope::putPostVar("ERROR", "Erro tentando incluir o arquivo $file");
		}
		Logger::debug("FileUtils.php", "Arquivo " . $file . " incluido com sucesso");
		return $result;
	}

	public static function readDirectory($directory, $recursive = false, $extension = null) {
		if( !is_dir($directory) ) return null;

		//Logger::debug("FileUtils","Lendo os arquivos do diretorio '$directory'");

		$files = array();

		$temp = scandir($directory);

		foreach( $temp as $dir ) {
			$file = $directory . "/" . $dir;

			//Logger::debug("FileUtils","Varrendo o diretorio : '$file'");

			if( is_file( $file ) ) {
				if( $extension != null ) {
					$fileExtension = substr( $file, strlen($file) - strlen($extension), strlen($file) );

					//Logger::debug("FileUtils","Arquivo encontrado : '$file'");
					//Logger::debug("FileUtils","Extensao do arquivo : '$fileExtension'");

					if( $fileExtension == $extension ) {
						$files[] = $file;
					}
				} else {
					$files[] = $file;
				}
			} else if( is_dir($file) && substr($file, strlen($file)- 1) != "." && substr($file, strlen($file)- 2) != ".." ) {
				$local = self::readDirectory($dir, $recursive, $extension);

				if( sizeof($local) > 0 ) {
					$files = array_merge($files, $local);
				}
			}
		}
		return $files;
	}
}
?>